package org.farm2.service.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.farm2.base.domain.FarmUserContext;
import org.farm2.base.domain.FarmUserContextLoader;
import org.farm2.files.domain.ResourceFile;
import org.farm2.files.service.ResourceFileServiceInter;
import org.farm2.files.utils.FileDownloadUtils;
import org.farm2.view.domain.GraphDto;
import org.farm2.tools.web.FarmResponseCode;
import org.farm2.tools.web.FarmResponseResult;
import org.farm2.view.domain.GraphPart;
import org.farm2.view.service.GraphPartServiceInter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 知识
 *
 * @author cbtg自动生成  2025-2-4 12:13:51
 */
@RestController
@RequestMapping("/api/wgraph")
public class WebGraphController {
    @Autowired
    private GraphPartServiceInter graphPartServiceImpl;
    @Autowired
    private ResourceFileServiceInter resourceFileServiceImpl;
    @Autowired
    private FileDownloadUtils fileDownloadUtils;

    /**
     * 加载知识内容
     *
     * @param graph
     * @return
     */
    @PostMapping("/add")
    public FarmResponseResult view(@RequestBody GraphDto graph) {
        GraphPart gpart = null;
        if (StringUtils.isBlank(graph.getId())) {
            gpart = graphPartServiceImpl.addGraph(graph);
        } else {
            gpart = graphPartServiceImpl.editGraph(graph);
        }
        return FarmResponseResult.getInstance(FarmResponseCode.SUCESS, gpart);
    }

    @PostMapping("/load")
    public FarmResponseResult load(@RequestBody GraphDto id) {
        GraphPart gpart = graphPartServiceImpl.getGraphPartById(id.getId());
        String text = graphPartServiceImpl.getDataJson(gpart.getDatafileid());
        Map<String, String> data = new HashMap<>();
        data.put("id", gpart.getId());
        data.put("dataJson", text);
        return FarmResponseResult.getInstance(FarmResponseCode.SUCESS, data);
    }


    @GetMapping("/download/{id}")
    public void downloadFile(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        GraphPart part = graphPartServiceImpl.getGraphPartById(id);
        ResourceFile rfile = resourceFileServiceImpl.getResourceFileById(part.getViewimgid());
        File file = resourceFileServiceImpl.getFile(rfile);
        FarmUserContext userContext = FarmUserContextLoader.getCurrentUser();
        if (rfile.getFilesize() > 104857600) {
            fileDownloadUtils.rangeStreamDownloadFile(request, response, file, rfile.getTitle(), "application/octet-stream");
        } else {
            fileDownloadUtils.simpleDownloadFile(file, rfile.getTitle(), "application/octet-stream", response, false);
        }
    }
}
